<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
      <!-- 添加角色按钮 -->
      <el-button type="primary">添加角色</el-button>
      <!-- 渲染角色列表 -->
      <el-table :data="allRoleList" border>
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row
              v-for="(item1,index) in scope.row.children"
              :key="item1.id"
              :class="['bdbottom',index===0?'bdtop':'']"
              type="flex"
              align="middle"
            >
              <!--遍历显示一级权限 -->
              <el-col :span="5">
                <el-tag closable @close="deleteAppointRights(scope.row,item1.id)">{{item1.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 遍历显示二、三级权限 -->
              <el-col :span="19">
                <el-row
                  v-for="(item2,index) in item1.children"
                  :key="item2.id"
                  :class="[index===0?'':'bdtop']"
                  type="flex"
                  align="middle"
                >
                  <!-- 二级权限 -->
                  <el-col :span="6">
                    <el-tag
                      type="success"
                      closable
                      @close="deleteAppointRights(scope.row,item2.id)"
                    >{{item2.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- 三级权限 -->
                  <el-col :span="18">
                    <el-tag
                      type="warning"
                      closable
                      @close="deleteAppointRights(scope.row,item3.id)"
                      v-for="item3 in item2.children"
                      :key="item3.id"
                    >{{item3.authName}}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
            <!-- <pre>{{scope.row}}</pre> -->
          </template>
        </el-table-column>
        <el-table-column label="#" type="index"></el-table-column>
        <el-table-column prop="roleName" label="角色名称"></el-table-column>
        <el-table-column prop="roleDesc" label="角色描述"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" icon="el-icon-edit">编辑</el-button>
            <el-button size="mini" type="danger" icon="el-icon-delete">删除</el-button>
            <el-button
              size="mini"
              type="warning"
              icon="el-icon-setting"
              @click="showCheckedRights(scope.row)"
            >设置</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 设置角色权限对话框 -->
    <el-dialog title="设置角色权限" :visible.sync="setDialogVisible" width="50%">
      <el-tree
        :data="allRightsData"
        :props="rightsProps"
        show-checkbox
        default-expand-all
        node-key="id"
        :default-checked-keys="defaultCheckedKeys"
        ref="rightsTree"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotAppointRights(roleId)">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 存放所有角色信息的数组
      allRoleList: [],
      // 设置角色权限对话框
      setDialogVisible: false,
      // 所有权限信息
      allRightsData: [],
      // 权限属性
      rightsProps: {
        children: 'children',
        label: 'authName'
      },
      // 默认被选中权限数组
      defaultCheckedKeys: [],
      // 角色id
      roleId: ''
    }
  },
  created() {
    this.getRoleList()
  },
  methods: {
    // 获取角色列表
    async getRoleList() {
      const res = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        return this.$message.error('获取角色列表失败')
      }
      this.$message.success('获取角色列表成功')
      this.allRoleList = res.data
    },
    // 删除角色指定权限
    async deleteAppointRights(role, rightsId) {
      const res = await this.$http.delete(`roles/${role.id}/rights/${rightsId}`)
      if (res.meta.status !== 200) {
        return this.$message.error('取消权限失败')
      }
      this.$message.success('取消权限成功')
      // 为了防止重新绘制整个页面，使用基于数据驱动的方式渲染页面
      role.children = res.data
    },
    // 获取所有权限列表
    async getAllRightsList() {
      const res = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) {
        return this.$message.error('获取权限列表失败')
      }
      // 获取权限列表成功
      this.allRightsData = res.data
    },
    // 渲染已经被选中的权限
    showCheckedRights(role) {
      // 设置角色id
      this.roleId = role.id
      // 一开始就清空defaultCheckedKeys
      this.defaultCheckedKeys = []
      // 获取权限列表
      this.getAllRightsList()
      // 设置默认选中权限
      this.getDefaultcheckedKeys(role, this.defaultCheckedKeys)
      // 打开对话框
      this.setDialogVisible = true
    },
    // 获得默认选中权限
    getDefaultcheckedKeys(node, keys) {
      // 如果结点不存在children属性，说明节点为三级结点
      if (!node.children) {
        // 将所有三级结点得id存入keys数组
        return keys.push(node.id)
      }
      // 递归结点
      node.children.forEach(item => this.getDefaultcheckedKeys(item, keys))
    },
    // 分配指定权限
    async allotAppointRights(roleId) {
      // 获取全选或半选中权限的id
      const arr1 = this.$refs.rightsTree.getCheckedKeys()
      const arr2 = this.$refs.rightsTree.getHalfCheckedKeys()
      // 将上述两个数组转换成字符串
      const rids = [...arr1, ...arr2].join(',')
      // 提交更新后的权限
      const res = await this.$http.post(`roles/${roleId}/rights`, { rids })
      if (res.meta.status !== 200) {
        this.$message.error('分配权限失败')
      }
      this.$message.success('分配权限成功')
      // 重新获取角色列表
      this.getRoleList()
      // 关闭对话框
      this.setDialogVisible = false
    }
  }
}
</script>

<style lang="less" scoped>
.el-tag {
  margin: 7px;
}
.bdtop {
  border-top: 1px solid #eee;
}
.bdbottom {
  border-bottom: 1px solid #eee;
}
</style>